package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.ResLossData;
import com.xmy.cultivate.entity.views.SelectStudent;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.QuarterRs;
import com.xmy.cultivate.respons.ResTranscriptScore;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 学生表 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-26
 */
@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;

    @Value("${aliyun.tts.appKey}")
    private String appkey;

    @Value("${aliyun.tts.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.tts.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    DictMapper dictMapper;

    @Autowired
    @Lazy
    ITypeValueDataService iTypeValueDataService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;

    @Autowired
    @Lazy
    IStudentFaceDataService iStudentFaceDataService;

    @Autowired
    @Lazy
    IWecharsBindService iWecharsBindService;

    @Autowired
    @Lazy
    IAliyunFaceService iAliyunFaceService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    ITranscriptService iTranscriptService;

    @Autowired
    @Lazy
    IStudentAccountService iStudentAccountService;

    @Value("${aliyun.face.DbName}")
    String faceDbname;

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    IRepairCourseService iRepairCourseService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IStudentSignInService iStudentSignInService;

    @Autowired
    @Lazy
    IDealInfoService iDealInfoService;

    @Autowired
    @Lazy
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    @Lazy
    IEnrollDataService iEnrollDataService;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    IServiceFeedbackService iServiceFeedbackService;

    @Autowired
    @Lazy
    IFaceDbService iFaceDbService;

    @Autowired
    @Lazy
    IRatePayService iRatePayService;

    @Autowired
    @Lazy
    IStudentLessonNumService iStudentLessonNumService;

    @Autowired
    @Lazy
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
    @Lazy
    IOssUploadService iOssUploadService;

    @Autowired
    @Lazy
    IStudentAudioService iStudentAudioService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    TypeValueDataMapper typeValueDataMapper;

    @Autowired
    @Lazy
    IAliyunApiService iAliyunApiService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    IStudentReadSchoolService iStudentReadSchoolService;

    @Autowired
    StudentReadSchoolMapper studentReadSchoolMapper;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    IStudentAllotTierSetService iStudentAllotTierSetService;


    public IPage<Student> findAll(IPage<?> page, Wrapper wrapper, Long schoolId) {

        IPage<Student> studentIPage = studentMapper.findAll(page, wrapper);
        for (Student student : studentIPage.getRecords()) {
            // as b where b.status <> 2 and b.residue_course_count>0 and b.student_id = a.id and a.deleted=0
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.ne("status", 2);
            studentQueryWrapper.eq("deleted", 0);
            studentQueryWrapper.gt("residue_course_count", 0);
            studentQueryWrapper.eq("student_id", student.getId());
            Integer count = studentMapper.getApplyCourseCount(studentQueryWrapper);
            if (schoolId.equals(0L)) {
                schoolId = student.getSchoolId();
            }
            if (iStudentFaceDataService.isGather(schoolId, student.getId())) {
                student.setIsGather(1);
            } else {
                student.setIsGather(0);
            }
            student.setApplyCourseCount(count);
        }

        return studentIPage;
    }

    public IPage<Student> rosterList(IPage<?> page, Integer yearPart, Integer quarterNum, Long schoolId, String schoolIdStr, String state, String isGuanzhu, String isGather, String isOwn, String isIdCard, String isCourseHouse, String isScheduling, String keywordType, String keyWord, Integer sourseLeve, Long adminId) {

        IPage<Student> studentIPage = studentMapper.rosterList(page, yearPart, quarterNum, schoolId, schoolIdStr, state, isGuanzhu, isGather, isOwn, isIdCard, isCourseHouse, isScheduling, keywordType, keyWord, sourseLeve, adminId);

        for (Student student : studentIPage.getRecords()) {
            if (schoolId.equals(0L)) {
                schoolId = student.getSchoolId();
            }
            if (iStudentFaceDataService.isGather(schoolId, student.getId())) {
                student.setIsGather(1);
            } else {
                student.setIsGather(0);
            }
            StudentAccount studentAccount = iStudentAccountService.getOneForStudentId(student.getId());
            if (studentAccount != null) {
                student.setStudentAccount(studentAccount.getAccount());
                student.setStudentPwd(studentAccount.getPwd());
            }

            // 查找每个学生的电话号码
            List<TypeValueData> typeValueDataList = iTypeValueDataService.list(new QueryWrapper<TypeValueData>().eq("for_id", student.getId()));
            student.setLinkManList(typeValueDataList);


            // 在读校区（公立）查询
            List<String> schoolNameList = studentReadSchoolMapper.readSchoolNameByStudentIdList(student.getId());
            if (schoolNameList != null && schoolNameList.size() > 0) {
                student.setReadingSchoolNameList(schoolNameList);
            }

        }
        return studentIPage;
    }

    /**
     * 花名册导出
     *
     * @return
     */
    @Override
    public IPage<Student> rosterListExcel(IPage<?> page, Integer yearPart, Integer quarterNum, Long schoolId, String schoolIdStr, String state, String isGuanzhu, String isGather, String isOwn, String isIdCard, String isCourseHouse, String isScheduling, String keywordType, String keyWord, Integer sourseLeve, Long adminId, String studentId) {
        IPage<Student> studentIPage = studentMapper.rosterListExcel(page, yearPart, quarterNum, schoolId, schoolIdStr, state, isGuanzhu, isGather, isOwn, isIdCard, isCourseHouse, isScheduling, keywordType, keyWord, sourseLeve, adminId, studentId);

        for (Student student : studentIPage.getRecords()) {
            if (schoolId.equals(0L)) {
                schoolId = student.getSchoolId();
            }
            if (iStudentFaceDataService.isGather(schoolId, student.getId())) {
                student.setIsGather(1);
            } else {
                student.setIsGather(0);
            }
            StudentAccount studentAccount = iStudentAccountService.getOneForStudentId(student.getId());
            if (studentAccount != null) {
                student.setStudentAccount(studentAccount.getAccount());
            }

            // 查找每个学生的电话号码
            List<TypeValueData> typeValueDataList = iTypeValueDataService.list(new QueryWrapper<TypeValueData>().eq("for_id", student.getId()));
            student.setLinkManList(typeValueDataList);

        }
        return studentIPage;
    }


    /**
     * 获取欠费
     *
     * @param wrapper
     * @return
     */
    public BigDecimal arrearage(Wrapper wrapper) {
        return studentMapper.arrearage(wrapper);
    }

    public IPage<Student> signUpStu(IPage<?> page, Wrapper wrapper) {
        return this.signUpStu(page, wrapper);
    }

    public Student findOne(@Param("id") Long id) {
        Quarter quarter = iQuarterService.getNowQuarter();
        Quarter quarterLast = iQuarterService.getLastQuarter(quarter.getYearPart(), quarter.getNum());
        //如果上个学期是假期，再获取上个学期
        if (quarterLast.getType().equals(2)) {
            quarterLast = iQuarterService.getLastQuarter(quarterLast.getYearPart(), quarterLast.getNum());
        }

        Student student = studentMapper.findOne(id);
        QueryWrapper<TypeValueData> typeValueDataQueryWrapper = new QueryWrapper<>();
        typeValueDataQueryWrapper.eq("for_id", student.getId());
        typeValueDataQueryWrapper.eq("type", 4);
        List<TypeValueData> typeValueList = iTypeValueDataService.list(typeValueDataQueryWrapper);
        student.setLinkManList(typeValueList);
        /*QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();
        transcriptQueryWrapper.eq("student_id",student.getId());
        transcriptQueryWrapper.eq("year_part",quarterLast.getYearPart());
        transcriptQueryWrapper.eq("quarter_num",quarterLast.getNum());
        transcriptQueryWrapper.eq("exam_num",3);//期末
        transcriptQueryWrapper.orderByAsc("subjects_id");*/
        Integer examNum = 3;//学期

        //七年级秋季班录入的成绩为市模拟成绩
        if (student.getYearClassId().equals(7) && quarter.getNum().equals(4)){
            if (examNum.equals(3)){
                examNum = 5;
            }
        }

        // 上学期期末
        List<ResTranscriptScore> transcriptList1 = iTranscriptService.getStudentScore(quarterLast.getYearPart(), quarterLast.getNum(), student.getId(), examNum);
        // 本学期期中
        List<ResTranscriptScore> transcriptList2 = iTranscriptService.getStudentScore(quarter.getYearPart(), quarter.getNum(), student.getId(), 1);

        List<ResTranscriptScore> subjectsScoreList = new ArrayList<>();
        ResTranscriptScore resTranscriptScore1 = new ResTranscriptScore();
        resTranscriptScore1.setExamNum(examNum);
        resTranscriptScore1.setResTranscriptScoreList(transcriptList1);

        ResTranscriptScore resTranscriptScore2 = new ResTranscriptScore();
        resTranscriptScore2.setExamNum(1);
        resTranscriptScore2.setResTranscriptScoreList(transcriptList2);

        subjectsScoreList.add(resTranscriptScore1);
        subjectsScoreList.add(resTranscriptScore2);

        student.setTranscriptList(subjectsScoreList);

        return student;
    }

    @Transactional
    public Boolean saveTo(Student student) {

        student.setId(idWorker.nextId());
        student.setGradeId(student.getYearClassId());

        List<TypeValueData> typeValueDataList = new ArrayList<>();

        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();
        Integer i = 0;
        while (iterator.hasNext()) {
            TypeValueData typeValueData = iterator.next();
            if (typeValueData.getTypeId() != null) {
                typeValueData.setForId(student.getId());
                typeValueData.setType(4);
                typeValueData.setContent(typeValueData.getContent().trim());
                typeValueDataList.add(typeValueData);
                if (i == 0) {
                    QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("num", typeValueData.getTypeId());
                    queryWrapper.eq("type", 4);
                    Dict dict = dictMapper.selectOne(queryWrapper);
                    if (dict != null) {
                        student.setLinkman(dict.getName());
                        student.setLinkmanPhone(typeValueData.getContent().trim());
                    }
                }
                i++;
            }
        }

        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        studentMapper.insert(student);
        //生成音频
        if (student.getName() != null && !student.getName().isEmpty()) {
            iAliyunApiService.ttsProcessGETRequet(student);
        }
        iStudentSchoolService.addOrUpdateData(student.getId(), student.getSchoolId());
        this.addWxBand(student.getId(), student.getLinkmanPhone());
        //添加分数
        iTranscriptService.addTrascript(student);

        /**
         * 试听
         */
        if (student.getStuType() != null && student.getStuType().equals(2)) {
            Quarter quarterNow = iQuarterService.getNowQuarter();
            //3个科目
            for (Integer j = 1; j <= 3; j++) {
                FaceGetScheduling faceGetScheduling = iStudentSignInService.getTryListenData(student, j.toString(), 1, quarterNow);
                if (faceGetScheduling.getLessonType().equals(1) && faceGetScheduling.getCourseType().equals(8)) {
                    iRecordCourseService.addTryListenData(faceGetScheduling, quarterNow, student.getCreatedId());
                }
            }
            iMqPushService.updateInviteDetailSigin(student);
        }

        return true;
    }

    public boolean addWxBand(Long studentId, String phone) {
        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.eq("phone", phone);
        wecharsBindQueryWrapper.eq("student_id", studentId);
        wecharsBindQueryWrapper.eq("type", 1);
        Long count = iWecharsBindService.count(wecharsBindQueryWrapper);
        if (count.equals(0L)) {
            wecharsBindQueryWrapper = new QueryWrapper<>();
            wecharsBindQueryWrapper.eq("phone", phone);
            wecharsBindQueryWrapper.eq("type", 1);
            wecharsBindQueryWrapper.last("limit 1");
            WecharsBind wecharsBindInfo = iWecharsBindService.getOne(wecharsBindQueryWrapper);
            if (wecharsBindInfo != null) {
                WecharsBind wecharsBindAdd = new WecharsBind();
                wecharsBindAdd.setId(idWorker.nextId());
                wecharsBindAdd.setPhone(phone);
                wecharsBindAdd.setStudentId(studentId);
                wecharsBindAdd.setOpenid(wecharsBindInfo.getOpenid());
                wecharsBindAdd.setUnionid(wecharsBindInfo.getUnionid());
                iWecharsBindService.save(wecharsBindAdd);
                UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();
                studentUpdateWrapper.eq("id", studentId);
                studentUpdateWrapper.set("is_guanzhu", 1);
                studentMapper.update(null, studentUpdateWrapper);
            }
        }
        return true;
    }

    /*
    public boolean addFaceData(Long schoolId,Long studentId){
        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("school_id",schoolId);
        studentFaceDataQueryWrapper.eq("student_id",studentId);

        Long count = iStudentFaceDataService.count(studentFaceDataQueryWrapper);
        if (count.equals(0)){
            studentFaceDataQueryWrapper = new QueryWrapper<>();
            studentFaceDataQueryWrapper.eq("student_id",studentId);
            studentFaceDataQueryWrapper.last("limit 3");
            List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);
            for (StudentFaceData studentFaceData:studentFaceDataList){
                if(iAliyunFaceService.existFaceSample(Long.parseLong(schoolId),faceDb.getDbName(),student.getId().toString())){
                    iAliyunFaceService.updateFaceSample(Long.parseLong(schoolId),faceDb.getDbName(),student.getId().toString(),student.getName());//添加人脸样本
                }else {
                    iAliyunFaceService.addFaceSample(Long.parseLong(schoolId),faceDb.getDbName(),student.getId().toString(),student.getName());//添加人脸样本
                }

                student.setIsGather(1);//设置为已采集
                QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();

                studentFaceDataQueryWrapper.eq("school_id",schoolId);
                studentFaceDataQueryWrapper.eq("student_id",student.getId());
                studentFaceDataQueryWrapper.eq("entity_id",student.getId());
                studentFaceDataQueryWrapper.orderByAsc("created_at");
                List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);

                AddFaceResponse addFaceResponse =null;
                String extraData = student.getName().trim();
                if(studentFaceDataList.size()>=5){
                    StudentFaceData studentFaceData = studentFaceDataList.get(0);
                    studentFaceData.getEntityId();
                    if(studentFaceData.getFaceId() !=null){
                        iAliyunFaceService.delFaceData(Long.parseLong(schoolId),faceDb.getDbName(),studentFaceData.getFaceId().toString());
                        iStudentFaceDataService.removeById(studentFaceData.getId());
                        addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId),faceDb.getDbName(),ossImageUrl,student.getId().toString(),extraData);//添加人脸数据
                        System.out.println("addFaceResponse2");
                        System.out.println(addFaceResponse);
                    }
                }else {
                    addFaceResponse = iAliyunFaceService.addFaceData(Long.parseLong(schoolId),faceDb.getDbName(),ossImageUrl,student.getId().toString(),extraData);//添加人脸数据
                    System.out.println("addFaceResponse");
                    System.out.println(addFaceResponse);
                }
                if(addFaceResponse !=null && addFaceResponse.getBody() !=null && addFaceResponse.getBody().getData() != null){
                    StudentFaceData studentFaceData = new StudentFaceData();
                    studentFaceData.setSchoolId(Long.parseLong(schoolId));
                    studentFaceData.setStudentId(student.getId());
                    studentFaceData.setEntityId(student.getId());
                    studentFaceData.setOssImage(ossImageUrl);
                    studentFaceData.setFaceId(addFaceResponse.getBody().getData().faceId);
                    studentFaceData.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
                    studentFaceData.setImage(directoryName+"/"+filename);
                    iStudentFaceDataService.save(studentFaceData);

                    //修改学生状态
                    student.setHeadImg(ossImageUrl);
                    student.setIsGather(1);
                    student.setEntityId(student.getId().toString());
                    iStudentService.updateById(student);
                    mapResult.put("signCode","10001");
                    return new Result(Code.OK,mapResult,"人脸采集成功");
                }
            }
        }
        return true;
    }
*/

    public boolean updateTo(Student student) {
        student.setGradeId(student.getYearClassId());

        List<TypeValueData> typeValueDataList = new ArrayList<>();
        List<TypeValueData> upTypeValueDataList = new ArrayList<>();
        Set<Long> atTypeValueData = new HashSet<>();

        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();

        while (iterator.hasNext()) {
            TypeValueData typeValueData = iterator.next();
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("num", typeValueData.getTypeId());
            queryWrapper.eq("type", 4);
            Dict dict = dictMapper.selectOne(queryWrapper);
            if (dict != null) {
                student.setLinkman(dict.getName());
                student.setLinkmanPhone(typeValueData.getContent().trim());
            }
            break;
        }

        //删除
        if (atTypeValueData.size() > 0) {
            QueryWrapper<TypeValueData> queryWrapper = new QueryWrapper<>();
            queryWrapper.notIn("id", atTypeValueData);
            queryWrapper.eq("for_id", student.getId());
            iTypeValueDataService.remove(queryWrapper);
        }
        //新增
        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //修改
        if (upTypeValueDataList.size() > 0) {
            iTypeValueDataService.updateBatchById(upTypeValueDataList, upTypeValueDataList.size());
        }

        //修改主体
        studentMapper.updateById(student);
        //生成音频
        if (student.getName() != null && !student.getName().isEmpty()) {
//            Student selectById = studentMapper.selectById(student.getId());
//            if (!Objects.equals(selectById.getName(), student.getName()) || selectById.getNameAudioPath().isEmpty()) {
            iAliyunApiService.ttsProcessGETRequet(student);
//            }
        }
        //添加成绩
        iTranscriptService.addTrascript(student);
        return true;
    }


    public Boolean updatePhoneNumNew(String id, Student student) {
        List<TypeValueData> typeValueDataList = new ArrayList<>();
        List<TypeValueData> upTypeValueDataList = new ArrayList<>();
        Set<Long> atTypeValueData = new HashSet<>();

        for (TypeValueData typeValueData : student.getLinkManList()) {
            typeValueData.setContent(typeValueData.getContent().trim());

            // 后台员工手机号验证
            Integer staffCount = iStaffService.staffCountByPhone(typeValueData.getContent().trim());
            if (staffCount != null && staffCount > 0) {
                throw new CommonException(ResultCode.PHONE_IS_TEACHER);
            }

            // 手机号绑定次数验证
            Integer studentCount = typeValueDataMapper.studentCountByPhone(typeValueData.getContent().trim());
            if (studentCount != null && studentCount > 2) {
                throw new CommonException(ResultCode.PHONE_IS_REPEATEDLY);
            }

            if (typeValueData.getTypeId() != null) {
                if (typeValueData.getId() == null || typeValueData.getTypeId() == 0) {
                    // 新增
                    typeValueData.setId(idWorker.nextId());
                    typeValueData.setForId(Long.parseLong(id));
                    typeValueData.setType(4);
                    typeValueDataList.add(typeValueData);
                } else {
                    // 修改
                    typeValueData.setForId(Long.parseLong(id));
                    typeValueData.setType(4);
                    upTypeValueDataList.add(typeValueData);
                    atTypeValueData.add(typeValueData.getId());
                }
            }
        }

        //删除
        if (atTypeValueData.size() > 0) {
            QueryWrapper<TypeValueData> queryWrapper = new QueryWrapper<>();
            queryWrapper.notIn("id", atTypeValueData);
            queryWrapper.eq("for_id", student.getId());
            iTypeValueDataService.remove(queryWrapper);
        }
        //新增
        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //修改
        if (upTypeValueDataList.size() > 0) {
            iTypeValueDataService.updateBatchById(upTypeValueDataList, upTypeValueDataList.size());
        }

        return true;
    }

    public String updatePhoneNum(String id, Student student) {
        // 这个是如果手机号不对只不保存这个手机号，其余手机号正常修改和保存
        List<TypeValueData> typeValueDataList = new ArrayList<>();
        List<TypeValueData> upTypeValueDataList = new ArrayList<>();
        Set<Long> atTypeValueData = new HashSet<>();

        StringBuilder sb = new StringBuilder();

        for (TypeValueData typeValueData : student.getLinkManList()) {
            typeValueData.setContent(typeValueData.getContent().trim());

            // 后台员工手机号验证
            Integer staffCount = iStaffService.staffCountByPhone(typeValueData.getContent().trim());
            if (staffCount != null && staffCount > 0) {
                sb.append(typeValueData.getContent() + "：教师手机号无法绑定学员");
                continue;
//                throw new CommonException(ResultCode.PHONE_IS_TEACHER);
            }

            // 手机号绑定次数验证
            Integer studentCount = typeValueDataMapper.studentCountByPhone(typeValueData.getContent().trim());
            if (studentCount != null && studentCount > 2) {
                sb.append(typeValueData.getContent() + "：该手机号绑定次数过多");
                continue;
//                throw new CommonException(ResultCode.PHONE_IS_REPEATEDLY);
            }

            if (typeValueData.getTypeId() != null) {
                if (typeValueData.getId() == 0) {
                    // 新增
                    typeValueData.setId(idWorker.nextId());
                    typeValueData.setForId(Long.parseLong(id));
                    typeValueData.setType(4);
                    typeValueDataList.add(typeValueData);
                } else {
                    // 修改
                    typeValueData.setForId(Long.parseLong(id));
                    typeValueData.setType(4);
                    upTypeValueDataList.add(typeValueData);
                    atTypeValueData.add(typeValueData.getId());
                }
            }
        }

        //删除
        if (atTypeValueData.size() > 0) {
            QueryWrapper<TypeValueData> queryWrapper = new QueryWrapper<>();
            queryWrapper.notIn("id", atTypeValueData);
            queryWrapper.eq("for_id", student.getId());
            iTypeValueDataService.remove(queryWrapper);
        }
        //新增
        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //修改
        if (upTypeValueDataList.size() > 0) {
            iTypeValueDataService.updateBatchById(upTypeValueDataList, upTypeValueDataList.size());
        }

        // 修改学员表的手机号
        List<TypeValueData> linkManList = student.getLinkManList();
        if (linkManList != null && !linkManList.isEmpty()) {
            String phoneNumber = linkManList.get(0).getContent(); // 获取下标为0的联系人的手机号

            if (linkManList.get(0).getTypeId() == 1) {
                student.setLinkman("父亲");
            } else if (linkManList.get(0).getTypeId() == 2) {
                student.setLinkman("母亲");
            } else if (linkManList.get(0).getTypeId() == 3) {
                student.setLinkman("本人");
            } else if (linkManList.get(0).getTypeId() == 4) {
                student.setLinkman("其他");
            }
            student.setLinkmanPhone(phoneNumber);
            studentMapper.updateById(student);

            // 调用mq同步到英语

        }

        if (sb.length() > 0) {
            return sb.toString();
        } else {
            return "成功";
        }
    }

   /* @Override
    public boolean updatePhoneNum(String id,Student student) {
        List<TypeValueData> typeValueDataList = new ArrayList<>();
        List<TypeValueData> upTypeValueDataList = new ArrayList<>();
        Set<Long> atTypeValueData = new HashSet<>();

        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();
        while (iterator.hasNext()) {
            TypeValueData typeValueData = iterator.next();
            typeValueData.setContent(typeValueData.getContent().trim());

            // 后台员工手机号验证
            Integer staffCount = iStaffService.staffCountByPhone(typeValueData.getContent().trim());
            if (staffCount != null && staffCount > 0) {
                throw new CommonException(ResultCode.PHONE_IS_TEACHER);
            }

            // 手机号绑定次数验证
            Integer studentCount = typeValueDataMapper.studentCountByPhone(typeValueData.getContent().trim());
            if (studentCount != null && studentCount > 2) {
                throw new CommonException(ResultCode.PHONE_IS_REPEATEDLY);
            }

        }

        Integer i = 0;
        while (iterator.hasNext()) {
            TypeValueData typeValueData = iterator.next();
            typeValueData.setContent(typeValueData.getContent().trim());

            if (typeValueData.getTypeId() != null) {
                if (typeValueData.getId() == 0) {
                    // 新增
                    typeValueData.setId(idWorker.nextId());
                    typeValueData.setForId(Long.parseLong(id));
                    typeValueData.setType(4);
                    typeValueDataList.add(typeValueData);
                } else {
                    // 修改
                    typeValueData.setForId(Long.parseLong(id));
                    typeValueData.setType(4);
                    upTypeValueDataList.add(typeValueData);
                    atTypeValueData.add(typeValueData.getId());
                }
                if (i == 0) {
                    QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("num", typeValueData.getTypeId());
                    queryWrapper.eq("type", 4);
                    Dict dict = dictMapper.selectOne(queryWrapper);
                    if (dict != null) {
                        student.setLinkman(dict.getName());
                        student.setLinkmanPhone(typeValueData.getContent().trim());
                    }
                }
                i++;
            }
        }

        //删除
        if (atTypeValueData.size() > 0) {
            QueryWrapper<TypeValueData> queryWrapper = new QueryWrapper<>();
            queryWrapper.notIn("id", atTypeValueData);
            queryWrapper.eq("for_id", student.getId());
            iTypeValueDataService.remove(queryWrapper);
        }
        //新增
        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //修改
        if (upTypeValueDataList.size() > 0) {
            iTypeValueDataService.updateBatchById(upTypeValueDataList, upTypeValueDataList.size());
        }

        return true;
    }*/

    public IPage<Student> getStudentForGradeId(Long gradeId, String name, Integer pageNum, Integer pageSize, String studentIdList, String status, String startDate, String endDate, Integer newTeacher, Long teacherId) {
        Grade grade = gradeMapper.selectById(gradeId);

        Quarter quarter = iQuarterService.getNowQuarter();

        Course course = courseMapper.selectById(grade.getCourseId());

        IPage<Student> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

        //where id in (select b.student_id from student_grade as b where b.grade_id = #{gradeId} and b.status = 1 and deleted = 0 and reading_status<>3)
        //studentGradeQueryWrapper.inSql("id","select b.student_id from student_grade as b where b.grade_id = "+gradeId+" and b.status <> 3 and deleted = 0 and (reading_status in(0,1,2,4,5,6) or (reading_status = 3 and use_course_count>0))");
        //studentGradeQueryWrapper.like(StringUtils.isNotBlank(name),"name",name);

        Integer yearPartAndQuarter = Integer.parseInt(quarter.getYearPart() + "" + quarter.getNum());//由从班级获取调整为从当前学期获取

        Quarter upQuarter = CommonUtil.getUpQuarter(grade.getYearPart(), grade.getQuarterNum());

        IPage<Student> studentList = studentMapper.getStudentForGradeId(iPage, gradeId, grade.getYearPart(), grade.getQuarterNum(), upQuarter.getYearPart(), upQuarter.getNum(), name, status, studentIdList, startDate, endDate, newTeacher, teacherId);
        for (Student student : studentList.getRecords()) {
            //OrderDetailTiny orderDetailTiny =  orderDetailMapper.getResidueCourseCountForCourseId(student.getId(),grade.getCourseId(),grade.getSchoolId());

            if (course != null) {

                Integer allCourseHouse = orderDetailMapper.getAllCouseHouse(grade.getSchoolId(), student.getId(), course.getSubjectsId(), quarter.getYearPart(), quarter.getNum(), grade.getLessonType());

                Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(grade.getSchoolId(), student.getId(), course.getSubjectsId(), yearPartAndQuarter, grade.getLessonType());
                student.setResidueCourseCount(residueCourseCount);
                student.setAllCourseCount(allCourseHouse);

                /*QueryWrapper<StudentGrade> studentGradeQueryWrapperForStudent = new QueryWrapper<>();
                studentGradeQueryWrapperForStudent.orderByDesc("created_at");
                studentGradeQueryWrapperForStudent.eq("deleted",0);
                studentGradeQueryWrapperForStudent.eq("grade_id",gradeId);
                studentGradeQueryWrapperForStudent.eq("student_id",student.getId());
                studentGradeQueryWrapperForStudent.ne("status",3);
                studentGradeQueryWrapperForStudent.last("limit 1");
                StudentGrade studentGrade = studentGradeMapper.selectOne(studentGradeQueryWrapperForStudent);*/
                String state = iStudentGradeService.studentAtGradeState(gradeId, student.getId(), 1);
                student.setState(state);
                String courseStatus = iStudentGradeService.getCourseStatus(gradeId, student.getId(), 1);
                student.setCourseStatus(Integer.parseInt(courseStatus));

                if (iStudentFaceDataService.isGather(grade.getSchoolId(), student.getId())) {
                    student.setIsGather(1);
                } else {
                    student.setIsGather(0);
                }

            } else {
                student.setResidueCourseCount(0);
                student.setAllCourseCount(0);
            }
            Integer userCourseCount = studentGradeMapper.useCourseCount(grade.getId(), student.getId());

            Integer arriveCount = userCourseCount - student.getRepairCount();

            student.setArriveCount(arriveCount);

            student.setUseCourseCount(userCourseCount);
            student.setClassId(gradeId);
            Long isCheckHouse = iStudentGradeService.isCheckHouse(grade.getId(), student.getId());
            student.setIsCheckHouse(isCheckHouse > 0 ? 0 : 1);
        }
        return studentList;
    }

    @Override
    public IPage<SelectStudent> getStudentForShift(IPage<?> page, QueryWrapper wrapper, Grade grade, String studentName, Long classTypeId) {

        Course course = courseMapper.selectById(grade.getCourseId());
        IPage<SelectStudent> selectStudentIPage;
        if (grade.getLessonType().equals(1)) {

            Quarter lastQuarter = iQuarterService.getLastQuarter(grade.getYearPart(),course.getQuarterNum());
            Integer lastYear = 0;
            Integer lastQuarterNum =0;
            if (lastQuarterNum!=null){
                lastYear = lastQuarter.getYearPart();
                lastQuarterNum = lastQuarterNum;
            }


            selectStudentIPage = studentMapper.getStudentForShift(page, wrapper, grade.getSchoolId(), grade.getCourseId(), grade.getYearPart(), course.getQuarterNum(),lastYear,lastQuarterNum,classTypeId);
            /*if (StringUtils.isNotBlank(studentName)){
                //所有的
                selectStudentIPage = studentMapper.getStudentForShift(page,wrapper,grade.getSchoolId(),grade.getCourseId(),grade.getYearPart(),course.getQuarterNum());
            }else {
                //分层查找
                selectStudentIPage = studentMapper.getStudentForShiftForClassType(page,wrapper,grade.getSchoolId(),grade.getCourseId(),grade.getYearPart(),course.getQuarterNum());
            }*/
        } else {
            selectStudentIPage = studentMapper.getStudentForShiftB(page, wrapper, grade.getSchoolId(), grade.getCourseId(), grade.getYearPart(), course.getQuarterNum());
        }

        for (SelectStudent selectStudent : selectStudentIPage.getRecords()) {
            selectStudent.setGradeId(grade.getId());
            if (selectStudent.getClassTypeIdStr()!=null){
                String classTypeNames =  iCourseTypeService.getClassTypeNames(selectStudent.getClassTypeIdStr());
                selectStudent.setClassTypeNames(classTypeNames);
            }
            Integer gradeSection = CommonUtil.getGradeSection(Integer.parseInt(selectStudent.getYearClassId()));
            StudentAllotTierSet studentAllotTierSet = iStudentAllotTierSetService.getAllotOne(selectStudent.getYearPart(),selectStudent.getQuarterNum(),Long.parseLong(selectStudent.getSubjectsId()),gradeSection,Integer.parseInt(selectStudent.getYearClassId()));
            if (studentAllotTierSet == null){
                studentAllotTierSet = new StudentAllotTierSet();
            }
            selectStudent.setStudentAllotTierSet(studentAllotTierSet);

            Quarter quarter = iQuarterService.getById(selectStudent.getPassShutQuarterId());

            QuarterRs quarterRs = new QuarterRs();
            if (quarter != null){
                quarterRs.setYearPart(quarter.getYearPart());
                quarterRs.setQuarterNum(quarter.getNum());
                quarterRs.setName(quarter.getAliasName());
            }
            selectStudent.setPassQuarter(quarterRs);

            quarter = iQuarterService.getById(selectStudent.getMidtermQuarterId());
            quarterRs = new QuarterRs();
            if (quarter != null){
                quarterRs.setYearPart(quarter.getYearPart());
                quarterRs.setQuarterNum(quarter.getNum());
                quarterRs.setName(quarter.getAliasName());
            }
            selectStudent.setMidtermQuarter(quarterRs);

            quarter = iQuarterService.getById(selectStudent.getEnTermQuarterId());
            quarterRs = new QuarterRs();
            if (quarter != null){
                quarterRs.setYearPart(quarter.getYearPart());
                quarterRs.setQuarterNum(quarter.getNum());
                quarterRs.setName(quarter.getAliasName());
            }
            selectStudent.setEndQuarter(quarterRs);

            //selectStudent.setHandleDate();
            selectStudent.setResidueCourseCount(orderDetailMapper.getResidueCourseHouseForCourseId(selectStudent.getStudentId(), grade.getCourseId(), grade.getSchoolId(), course.getLessonType()));
        }

        return selectStudentIPage;
    }

    /**
     * 获取预分班学员
     *
     * @param page
     * @param wrapper
     * @return
     */
    @Override
    public IPage<SelectStudent> getAllotStudent(IPage<?> page, Wrapper wrapper, Grade grade, Integer yearAndQuarter, Integer yearPart, Integer quarterNum, Integer lessonType,Long classTypeId) {
        Long schoolId = grade.getSchoolId();
        String schoolIdStr =  iSchoolQuarterService.getChilIdsForAlone(yearPart,quarterNum,schoolId.toString());

        Course course = courseMapper.selectById(grade.getCourseId());
        IPage<SelectStudent> selectStudentIPage = studentMapper.getAllotStudent(page, wrapper, schoolIdStr, course.getSubjectsId(), yearAndQuarter, yearPart, quarterNum, lessonType,classTypeId);
        for (SelectStudent selectStudent : selectStudentIPage.getRecords()) {
            selectStudent.setGradeId(grade.getId());
            if (selectStudent.getClassTypeIdStr()!=null){
               String classTypeNames =  iCourseTypeService.getClassTypeNames(selectStudent.getClassTypeIdStr());
                selectStudent.setClassTypeNames(classTypeNames);
            }
            Integer gradeSection = CommonUtil.getGradeSection(Integer.parseInt(selectStudent.getYearClassId()));
            StudentAllotTierSet studentAllotTierSet = iStudentAllotTierSetService.getAllotOne(selectStudent.getYearPart(),selectStudent.getQuarterNum(),Long.parseLong(selectStudent.getSubjectsId()),gradeSection,Integer.parseInt(selectStudent.getYearClassId()));
            if (studentAllotTierSet == null){
                studentAllotTierSet = new StudentAllotTierSet();
            }
            selectStudent.setStudentAllotTierSet(studentAllotTierSet);

            Quarter quarter = iQuarterService.getById(selectStudent.getPassShutQuarterId());

            QuarterRs quarterRs = new QuarterRs();
            if (quarter != null){
                quarterRs.setYearPart(quarter.getYearPart());
                quarterRs.setQuarterNum(quarter.getNum());
                quarterRs.setName(quarter.getAliasName());
            }
            selectStudent.setPassQuarter(quarterRs);

            quarter = iQuarterService.getById(selectStudent.getMidtermQuarterId());
            quarterRs = new QuarterRs();
            if (quarter != null){
                quarterRs.setYearPart(quarter.getYearPart());
                quarterRs.setQuarterNum(quarter.getNum());
                quarterRs.setName(quarter.getAliasName());
            }
            selectStudent.setMidtermQuarter(quarterRs);

            quarter = iQuarterService.getById(selectStudent.getEnTermQuarterId());
            quarterRs = new QuarterRs();
            if (quarter != null){
                quarterRs.setYearPart(quarter.getYearPart());
                quarterRs.setQuarterNum(quarter.getNum());
                quarterRs.setName(quarter.getAliasName());
            }
            selectStudent.setEndQuarter(quarterRs);

            /*Student student = studentMapper.selectById(selectStudent.getStudentId());
            if (student != null){
                selectStudent.setStudentName(student.getName());
            }*/
            //selectStudent.setHandleDate();
            //selectStudent.setResidueCourseCount(orderDetailMapper.getResidueCourseCountForSubjects(schoolId,selectStudent.getStudentId(),course.getSubjectsId(),yearAndQuarter,grade.getLessonType()));
        }
        return selectStudentIPage;
    }

    public boolean addGradeStudent(String gradeId, String[] studentList) {

        Grade grade = gradeMapper.getOneForId(Long.parseLong(gradeId));
        if (grade == null) {
            throw new CommonException(ResultCode.GRADE_NOT);
        }
        List<StudentGrade> studentGradeList = new ArrayList<>();
        for (String id : studentList) {
            Long studentId = Long.parseLong(id);
            OrderDetail orderDetail = orderDetailMapper.getLastOneForCourseId(grade.getSchoolId(), studentId, grade.getCourseId(), grade.getLessonType());
            if (orderDetail != null) {
                StudentGrade studentGrade = new StudentGrade();
                studentGrade.setOrderDetailId(orderDetail.getId());
                studentGrade.setStudentId(studentId);
                studentGrade.setSchoolId(grade.getSchoolId());
                studentGrade.setGradeId(grade.getId());
                studentGrade.setCourseId(grade.getCourseId());
                studentGrade.setSubjectsId(orderDetail.getSubjectsId());
                studentGrade.setRenewTeacherId(grade.getTeacherId());
                studentGrade.setYearPart(orderDetail.getYearPart());
                studentGrade.setQuarterNum(orderDetail.getQuarterNum());
                studentGrade.setSurplusCourseNum(orderDetail.getResidueCourseCount());
                studentGrade.setIsRenew(1);
                studentGradeList.add(studentGrade);
            }
        }
        if (studentGradeList.size() > 0) {
            iStudentGradeService.saveBatch(studentGradeList);
        }
        return true;
    }

    @Override
    public String getStudentName(Long id) {
        return studentMapper.getStudentName(id);
    }

    @Override
    public List<Student> getStudentCount(String schoolId, String subjectsId, String yearPart, String quarterNum, String courseTypeId, Integer status, String startDate, String endDate) {
        return studentMapper.getStudentCount(schoolId, subjectsId, yearPart, quarterNum, courseTypeId, status, startDate, endDate);
    }

    @Override
    public Integer getStudentCountByYearClassId(String schoolId, String subjectsId, String yearPart, String quarterNum, String courseTypeId, String yearClassId, Integer status, String startDate, String endDate) {
        return studentMapper.getStudentCountByYearClassId(schoolId, subjectsId, yearPart, quarterNum, courseTypeId, yearClassId, status, startDate, endDate);
    }

    @Override
    public Integer getStudentCountBySchoolId(String schoolId, String subjectsId, String yearPart, String quarterNum, String courseTypeId, Integer status, String startDate, String endDate) {
        return studentMapper.getStudentCountBySchoolId(schoolId, subjectsId, yearPart, quarterNum, courseTypeId, status, startDate, endDate);
    }

    @Override
    @Async("onlineAsync")
    public void updateStudentBatch() throws Exception {

        Integer faceType =1;
        List<Student> studentList = studentMapper.getRedoStudentList();
        Integer j = 0;
        for (Student student : studentList) {
            List<Student> studentList2 = studentMapper.getStudentListForIdCardNo(student.getIdCardNo(), student.getName());
            Long toStudentId = null;//获取出最后保留的学生id
            Integer i = 1;
            for (Student student2 : studentList2) {
                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                orderDetailQueryWrapper.eq("student_id", student2.getId());
                orderDetailQueryWrapper.eq("subjects_id", 1);
                Long count = iOrderDetailService.count(orderDetailQueryWrapper);
                if (toStudentId == null && count > 0) {
                    if (count > 0) {
                        toStudentId = student2.getId();
                    }
                }
                if (count > 0) {
                    QueryWrapper<StudentAccount> studentAccountQueryWrapper = new QueryWrapper<>();
                    studentAccountQueryWrapper.eq("student_id", student2.getId());
                    Long accountCount = iStudentAccountService.count(studentAccountQueryWrapper);
                    if (accountCount > 0) {
                        toStudentId = student2.getId();
                    }
                }
                if (i.equals(studentList2.size())) {
                    if (toStudentId == null) {
                        toStudentId = student2.getId();
                    }
                }
                i++;
            }
            for (Student student2 : studentList2) {
                if (student2.getId().equals(toStudentId)) {
                    continue;
                }
                Long studentId = student2.getId();
                Thread.sleep(2000);

                //log.error("toStudentId:"+toStudentId);
                //log.error("studentId:"+studentId);
                //log.error("studentName:"+student2.getName());
                this.updateStudentBatchAction(studentId, toStudentId,faceType);

                //student2.setRemark("删除");
                this.removeById(student2);

            }
            /*j++;
            log.info("studentName:"+student.getName());
            log.info("hostStudentId:"+hostStudentId);
            log.info(studentList.size()+"---"+j);*/
        }
    }

    public void updateStudentBatchAction(Long studentId, Long toStudentId, Integer faceType) throws Exception {
        UpdateWrapper<OrderApply> applyUpdateWrapper = new UpdateWrapper<>();
        applyUpdateWrapper.inSql("id", "select order_id from order_detail where  student_id = " + studentId);
        applyUpdateWrapper.set("student_id", toStudentId);
        iOrderApplyService.update(applyUpdateWrapper);

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("student_id", studentId);
        List<OrderDetail> orderDetailList = iOrderDetailService.list(orderDetailQueryWrapper);
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setStudentId(toStudentId);
            iOrderDetailService.updateById(orderDetail);
            Long schoolId = orderDetail.getSchoolId();
            boolean rs = iAliyunFaceService.delFaceSampleForEntityId(schoolId, this.faceDbname, studentId.toString());
            if (rs) {
            }
            iStudentFaceDataService.updateStudentFaceData(schoolId, studentId, toStudentId,faceType);
        }

        /*UpdateWrapper<OrderDetail> orderDetailUpdateWrapper = new UpdateWrapper<>();
        orderDetailUpdateWrapper.eq("student_id",studentId);
        orderDetailUpdateWrapper.set("student_id",toStudentId);
        iOrderDetailService.update(orderDetailUpdateWrapper);*/

        UpdateWrapper<RepairCourse> repairCourseUpdateWrapper = new UpdateWrapper<>();
        repairCourseUpdateWrapper.eq("student_id", studentId);
        repairCourseUpdateWrapper.set("student_id", toStudentId);
        iRepairCourseService.update(repairCourseUpdateWrapper);

        UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
        studentGradeUpdateWrapper.eq("student_id", studentId);
        studentGradeUpdateWrapper.set("student_id", toStudentId);
        iStudentGradeService.update(studentGradeUpdateWrapper);

        UpdateWrapper<StudentSignIn> studentSignInUpdateWrapper = new UpdateWrapper<>();
        studentSignInUpdateWrapper.eq("student_id", studentId);
        studentSignInUpdateWrapper.set("student_id", toStudentId);
        iStudentSignInService.update(studentSignInUpdateWrapper);

        UpdateWrapper<DealInfo> dealInfoUpdateWrapper = new UpdateWrapper<>();
        dealInfoUpdateWrapper.eq("student_id", studentId);
        dealInfoUpdateWrapper.set("student_id", toStudentId);
        iDealInfoService.update(dealInfoUpdateWrapper);

        UpdateWrapper<EnrollData> enrollDataUpdateWrapper = new UpdateWrapper<>();
        enrollDataUpdateWrapper.eq("student_id", studentId);
        enrollDataUpdateWrapper.set("student_id", toStudentId);
        iEnrollDataService.update(enrollDataUpdateWrapper);

        UpdateWrapper<EnrollInfo> enrollInfoUpdateWrapper = new UpdateWrapper<>();
        enrollInfoUpdateWrapper.eq("student_id", studentId);
        enrollInfoUpdateWrapper.set("student_id", toStudentId);
        iEnrollInfoService.update(enrollInfoUpdateWrapper);

        UpdateWrapper<StudentSchool> studentSchoolUpdateWrapper = new UpdateWrapper<>();
        studentSchoolUpdateWrapper.eq("student_id", studentId);
        studentSchoolUpdateWrapper.set("student_id", toStudentId);
        iStudentSchoolService.update(studentSchoolUpdateWrapper);


        /*UpdateWrapper<StudentType> studentTypeUpdateWrapper = new UpdateWrapper<>();
        studentTypeUpdateWrapper.eq("student_id",studentId);
        studentTypeUpdateWrapper.set("student_id",toStudentId);
        iStudentTypeService.update(studentTypeUpdateWrapper);*/
        QueryWrapper<StudentType> studentTypeQueryWrapper = new QueryWrapper<>();
        studentTypeQueryWrapper.eq("student_id", studentId);
        List<StudentType> studentTypeList = iStudentTypeService.list(studentTypeQueryWrapper);
        for (StudentType studentType : studentTypeList) {
            studentTypeQueryWrapper.clear();
            studentTypeQueryWrapper.eq("student_id", studentId);
            studentTypeQueryWrapper.eq("school_id", studentType.getSchoolId());
            studentTypeQueryWrapper.eq("subjects_id", studentType.getSubjectsId());

            Long count = iStudentTypeService.count(studentTypeQueryWrapper);
            if (count > 0) {
                continue;
            }
            studentType.setStudentId(toStudentId);
            iStudentTypeService.updateById(studentType);
        }


        UpdateWrapper<Transcript> transcriptUpdateWrapper = new UpdateWrapper<>();
        transcriptUpdateWrapper.eq("student_id", studentId);
        transcriptUpdateWrapper.set("student_id", toStudentId);
        iTranscriptService.update(transcriptUpdateWrapper);

        applyUpdateWrapper.clear();
        ;
        applyUpdateWrapper.eq("student_id", studentId);
        applyUpdateWrapper.set("student_id", toStudentId);
        iOrderApplyService.update(applyUpdateWrapper);

        UpdateWrapper<RatePay> ratePayUpdateWrapper = new UpdateWrapper<>();
        ratePayUpdateWrapper.eq("student_id", studentId);
        ratePayUpdateWrapper.set("student_id", toStudentId);
        iRatePayService.update(ratePayUpdateWrapper);

        UpdateWrapper<StudentLessonNum> studentLessonNumUpdateWrapper = new UpdateWrapper<>();
        studentLessonNumUpdateWrapper.eq("student_id", studentId);
        studentLessonNumUpdateWrapper.set("student_id", toStudentId);
        iStudentLessonNumService.update(studentLessonNumUpdateWrapper);

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("student_id", studentId);
        List<RecordCourse> recordCourseList = iRecordCourseService.list(recordCourseQueryWrapper);
        for (RecordCourse recordCourse : recordCourseList) {
            Long studentIdOld = recordCourse.getStudentId();
            try {
                recordCourse.setStudentId(toStudentId);
                iRecordCourseService.updateById(recordCourse);
            } catch (Exception e) {
                recordCourse.setRemark("合并冲突被删除");
                recordCourse.setStudentId(studentIdOld);
                iRecordCourseService.updateById(recordCourse);
                iRecordCourseService.removeById(recordCourse);
            }
        }

        QueryWrapper<StudentClassType> studentClassTypeQueryWrapper = new QueryWrapper<>();
        studentClassTypeQueryWrapper.eq("student_id", studentId);
        List<StudentClassType> studentClassTypeList = iStudentClassTypeService.list(studentClassTypeQueryWrapper);
        for (StudentClassType studentClassType : studentClassTypeList) {
            studentClassTypeQueryWrapper.clear();
            ;
            studentClassTypeQueryWrapper.eq("year_part", studentClassType.getYearPart());
            studentClassTypeQueryWrapper.eq("quarter_num", studentClassType.getQuarterNum());
            studentClassTypeQueryWrapper.eq("student_id", studentClassType.getStudentId());
            studentClassTypeQueryWrapper.eq("subjects_id", studentClassType.getSubjectsId());
            Long count = iStudentClassTypeService.count(studentClassTypeQueryWrapper);
            if (count.equals(0L)) {
                studentClassType.setStudentId(toStudentId);
                iStudentClassTypeService.updateById(studentClassType);
            } else {
                iStudentClassTypeService.removeById(studentClassType);
            }
        }



        /*UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
        recordCourseUpdateWrapper.eq("student_id",studentId);
        recordCourseUpdateWrapper.set("student_id",toStudentId);
        iRecordCourseService.update(recordCourseUpdateWrapper);

        UpdateWrapper<ServiceFeedback> serviceFeedbackUpdateWrapper = new UpdateWrapper<>();
        serviceFeedbackUpdateWrapper.eq("student_id",studentId);
        serviceFeedbackUpdateWrapper.set("student_id",toStudentId);
        iServiceFeedbackService.update(serviceFeedbackUpdateWrapper);
        */
        QueryWrapper<ServiceFeedback> serviceFeedbackQueryWrapper = new QueryWrapper<>();
        serviceFeedbackQueryWrapper.eq("student_id", studentId);
        List<ServiceFeedback> serviceFeedbackList = iServiceFeedbackService.list(serviceFeedbackQueryWrapper);
        for (ServiceFeedback serviceFeedback : serviceFeedbackList) {
            try {
                serviceFeedback.setStudentId(toStudentId);
                iServiceFeedbackService.updateById(serviceFeedback);
            } catch (Exception e) {
                iServiceFeedbackService.removeById(serviceFeedback);
            }
        }
    }

    /**
     * 获取学员流失数据
     *
     * @param subjectsId
     * @param lessonType
     * @param startQuarterId 学期开始id
     * @param endQuarterId   学期结束id
     * @return
     */
    @Override
    public ResLossData getLossData(Long subjectsId, Integer lessonType, Long startQuarterId, Long endQuarterId) {
        return studentMapper.getLossData(subjectsId, lessonType, startQuarterId, endQuarterId);
    }

    @Override
    @Async("onlineAsync")
    public void resetYearClassId() {
        List<OrderDetail> orderDetailList = iOrderDetailService.getLastOrderListForStudent();
        for (OrderDetail orderDetail : orderDetailList) {
            try {
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(orderDetail.getYearPart(), orderDetail.getQuarterNum());
                if (quarter != null) {
                    List<Quarter> quarterList = iQuarterService.getQuarterBigIdList(quarter.getId());
                    Integer i = 0;
                    Integer yearClassPlus = 0;
                    for (Quarter quarterInfo : quarterList) {
                        if (i.equals(0) && orderDetail.getQuarterNum().equals(3)) {
                            i++;
                            continue;
                        }
                        i++;
                        if (quarterInfo.getNum().equals(3)) {
                            yearClassPlus++;
                        }
                    }
                    Student student = this.getById(orderDetail.getStudentId());
                    Integer yearClassId = orderDetail.getYearClassId() + yearClassPlus;
                    if (student.getYearClassId() == null || !student.getYearClassId().equals(yearClassId)) {
                        student.setYearClassId(yearClassId);
                        this.updateById(student);
                    }

                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    public IPage<StudentGrade> getStudentIdByReading(IPage<?> page, String studentName) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(studentName), "t2.`name`", studentName);
//        wrapper.inSql("t1.reading_status","0,1");
        Quarter quarter = iQuarterService.getNowQuarter();
        wrapper.eq("t1.year_part", quarter.getYearPart());
        wrapper.eq("t1.quarter_num", quarter.getNum());
        wrapper.eq("t1.lesson_type", 1);
        wrapper.eq("t1.deleted", 0);
        wrapper.eq("t2.deleted", 0);
        wrapper.groupBy("t1.student_id");

        IPage<StudentGrade> studentGradeList = studentMapper.getStudentIdByReading(page, wrapper);

        return studentGradeList;
    }

    @Override
    public Integer getTryStudentForNameCount(String name, Long schoolId) {
        return studentMapper.getTryStudentForNameCount(name, schoolId);
    }

    @Override
    public void  addOrUpdateData(Student student){
        if (student.getId() != null){
            student.setId(idWorker.nextId());
        }
        List<TypeValueData> typeValueDataList = new ArrayList<>();

        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();
        Integer i = 0;
        while (iterator.hasNext()) {
            TypeValueData typeValueData = iterator.next();
            if (typeValueData.getTypeId() != null) {
                typeValueData.setForId(student.getId());
                typeValueData.setType(4);
                typeValueData.setContent(typeValueData.getContent().trim());
                typeValueDataList.add(typeValueData);
                if (i == 0) {
                    QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("num", typeValueData.getTypeId());
                    queryWrapper.eq("type", 4);
                    Dict dict = dictMapper.selectOne(queryWrapper);
                    if (dict != null) {
                        student.setLinkman(dict.getName());
                        student.setLinkmanPhone(typeValueData.getContent().trim());
                    }
                }
                i++;
            }
        }
        if (typeValueDataList.size() > 0) {
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //生成音频
        if (student.getName() != null && !student.getName().isEmpty()) {
            //iAliyunApiService.ttsProcessGETRequet(student);
        }
        this.saveOrUpdate(student);
        iStudentSchoolService.addOrUpdateData(student.getId(), student.getSchoolId());
    }


}
